package com.ivg.filter;

import com.ivg.constant.GateWayConstants;
import com.ivg.util.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * jwt filter
 */
public class JwtFilter extends ZuulFilter {

    private static final String BEARER_HEAD = "bearer;";


    @Value("${path.login}")
    private String loginPath;

    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * filter执行顺序, 通过数字指定, 优先级为0最高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启该filter
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String authHeader = request.getHeader("authorization");
        String path = request.getRequestURI();
        if(path.equals(loginPath)){
            authSuccess(ctx);
        }else {
            if(StringUtils.isEmpty(authHeader)){
                authFail(ctx,"no permission");
                return ctx;
            }
            String token = authHeader.substring(BEARER_HEAD.length());
            Claims claims = JwtUtil.parseJWT(token);
            if(checkClaims(ctx, claims)) {
                ctx.addZuulRequestHeader(GateWayConstants.HEADER_CURRENTUSER, token);
            }
        }
        return ctx;
    }

    private boolean checkClaims(RequestContext ctx, Claims claims) {
        Date expiration = claims.getExpiration();
        if (expiration.before(new Date())) {
            authFail(ctx, "token over time");
            return false;
        }
        return true;
    }


    private void authSuccess(RequestContext ctx) {
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        ctx.set("isSuccess", true);
    }

    private void authFail(RequestContext ctx, String errMsg) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(400);
        ctx.setResponseBody(errMsg);
        ctx.set("isSuccess", false);
    }
}
